import React, { useEffect, useRef, useState } from 'react';
import { fabric } from 'fabric';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '../store';
import { setCanvas, setFabricCanvas } from '../store/slices/imageSlice';
import { useImageProcess } from '../hooks/useImageProcess';
import FilterPanel from './FilterPanel';
import ToolPanel from './ToolPanel';

const ImageEditor: React.FC = () => {
  const dispatch = useDispatch();
  const { currentImage } = useSelector((state: RootState) => state.image);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const fabricCanvasRef = useRef<fabric.Canvas | null>(null);
  const [isCanvasReady, setIsCanvasReady] = useState(false);

  const { applyFilters, filters } = useImageProcess();

  useEffect(() => {
    if (canvasRef.current && !fabricCanvasRef.current) {
      // 初始化Fabric.js画布
      const canvas = new fabric.Canvas(canvasRef.current, {
        width: 800,
        height: 600,
        backgroundColor: '#f0f0f0',
      });

      fabricCanvasRef.current = canvas;
      dispatch(setCanvas(canvasRef.current));
      dispatch(setFabricCanvas(canvas));
      setIsCanvasReady(true);

      return () => {
        canvas.dispose();
        fabricCanvasRef.current = null;
      };
    }
  }, [dispatch]);

  useEffect(() => {
    if (currentImage && fabricCanvasRef.current && isCanvasReady) {
      // 加载图片到画布
      fabric.Image.fromURL(currentImage, (img) => {
        const canvas = fabricCanvasRef.current!;
        
        // 清除画布
        canvas.clear();
        
        // 调整图片大小以适应画布
        const canvasWidth = canvas.getWidth();
        const canvasHeight = canvas.getHeight();
        const imgWidth = img.width!;
        const imgHeight = img.height!;
        
        const scale = Math.min(
          canvasWidth / imgWidth,
          canvasHeight / imgHeight
        );
        
        img.scale(scale);
        img.center();
        
        canvas.add(img);
        canvas.renderAll();
      });
    }
  }, [currentImage, isCanvasReady]);

  useEffect(() => {
    // 应用滤镜效果
    if (fabricCanvasRef.current) {
      const canvas = fabricCanvasRef.current;
      const objects = canvas.getObjects();
      
      objects.forEach((obj) => {
        if (obj.type === 'image') {
          const imgObj = obj as fabric.Image;
          
          // 创建滤镜数组
          const filterArray: fabric.IBaseFilter[] = [];
          
          if (filters.brightness !== 0) {
            filterArray.push(new fabric.Image.filters.Brightness({
              brightness: filters.brightness / 100,
            }));
          }
          
          if (filters.contrast !== 0) {
            filterArray.push(new fabric.Image.filters.Contrast({
              contrast: filters.contrast / 100,
            }));
          }
          
          if (filters.blur > 0) {
            filterArray.push(new fabric.Image.filters.Blur({
              blur: filters.blur / 10,
            }));
          }
          
          imgObj.filters = filterArray;
          imgObj.applyFilters();
        }
      });
      
      canvas.renderAll();
    }
  }, [filters]);

  if (!currentImage) {
    return (
      <div className="flex items-center justify-center h-full bg-gray-100 dark:bg-gray-800 rounded-lg">
        <p className="text-gray-500 dark:text-gray-400 text-lg">
          请先上传一张图片
        </p>
      </div>
    );
  }

  return (
    <div className="flex h-full">
      {/* 工具面板 */}
      <div className="w-64 bg-white dark:bg-gray-900 border-r border-gray-200 dark:border-gray-700 p-4">
        <ToolPanel />
        <div className="mt-6">
          <FilterPanel />
        </div>
      </div>
      
      {/* 画布区域 */}
      <div className="flex-1 flex items-center justify-center bg-gray-50 dark:bg-gray-800 p-4">
        <div className="border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden shadow-lg">
          <canvas
            ref={canvasRef}
            className="block"
          />
        </div>
      </div>
    </div>
  );
};

export default ImageEditor;